package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Exit;
import com.ruoyi.system.entity.ExitNums;
import com.ruoyi.system.mapper.ExitMapper;
import com.ruoyi.system.service.IExitService;

/**
 * 退服表Service业务层处理
 * 
 * @author zhangkai
 * @date 2021-11-24
 */
@Service
public class ExitServiceImpl implements IExitService 
{
	private static final Logger log = LoggerFactory.getLogger(ExitServiceImpl.class);
    @Autowired
    private ExitMapper exitMapper;

    /**
     * 查询退服表
     * 
     * @param id 退服表主键
     * @return 退服表
     */
    @Override
    public Exit selectExitById(Long id)
    {
        return exitMapper.selectExitById(id);
    }

    /**
     * 查询退服表列表
     * 
     * @param exit 退服表
     * @return 退服表
     */
    @Override
    public List<Exit> selectExitList(Exit exit)
    {
        return exitMapper.selectExitList(exit);
    }

    /**
     * 新增退服表
     * 
     * @param exit 退服表
     * @return 结果
     */
    @Override
    public int insertExit(Exit exit)
    {
        exit.setCreateTime(DateUtils.getNowDate());
        return exitMapper.insertExit(exit);
    }

    /**
     * 修改退服表
     * 
     * @param exit 退服表
     * @return 结果
     */
    @Override
    public int updateExit(Exit exit)
    {
        exit.setUpdateTime(DateUtils.getNowDate());
        return exitMapper.updateExit(exit);
    }

    /**
     * 批量删除退服表
     * 
     * @param ids 需要删除的退服表主键
     * @return 结果
     */
    @Override
    public int deleteExitByIds(Long[] ids)
    {
        return exitMapper.deleteExitByIds(ids);
    }

    /**
     * 删除退服表信息
     * 
     * @param id 退服表主键
     * @return 结果
     */
    @Override
    public int deleteExitById(Long id)
    {
        return exitMapper.deleteExitById(id);
    }
    
    /**
     * 导入全站数据
     * 
     * @param totalList 全站数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importTotal(List<Exit> totalList,String operName,String dateRange)
    {
    	if(dateRange.equals("null")) {
    		throw new ServiceException("版本不能为空！");
    	}
    	String newDateRange = dateRange.replaceAll("-", "").replaceAll(":", "").replaceAll(" ", "").substring(0,12);
        if (StringUtils.isNull(totalList) || totalList.size() == 0)
        {
            throw new ServiceException("导入关键站址数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Exit site : totalList)
        {
            try
               {
            	    site.setVersion(newDateRange);
                    this.insertExit(site);
                    successNum++;
                //    successMsg.append("<br/>" + successNum + "、站址编码: " + site.getStationCode() + " 导入成功");
                }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、站址编码: " + site.getStationCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /* 缓存初始化 */
    private LoadingCache<String, String> maxCache = CacheBuilder.newBuilder().maximumSize(1000)
            .build(new CacheLoader<String, String>() {
                /* 加载缓存方法 */
                public String load(String key) throws InterruptedException {
                    /* 返回 */
                    return exitMapper.maxVersion();
                }
            });
    
	@Override
	public String maxVersion() {
		try {
            /* 调用缓存 */
            return maxCache.get("");
        } catch (ExecutionException e) {
            /* 记录日志 */
        	log.error(e.getMessage(), e);
        }
        /* 异常返回空 */
        return null;
	}
	
	/* 缓存初始化 */
    private LoadingCache<String, List<ExitNums>> numsCache = CacheBuilder.newBuilder().maximumSize(1000)
            .build(new CacheLoader<String, List<ExitNums>>() {
                /* 加载缓存方法 */
                public List<ExitNums> load(String key) throws InterruptedException {
                    /* 返回 */
                    return exitMapper.getNums(key);
                }
            });

	@Override
	public List<ExitNums> getNums(String version) {
		try {
            /* 调用缓存 */
            return numsCache.get(version);
        } catch (ExecutionException e) {
            /* 记录日志 */
        	log.error(e.getMessage(), e);
        }
        /* 异常返回空 */
        return null;
	}

	@Override
	public void cacheClean() {
		maxCache.invalidateAll();
		numsCache.invalidateAll();
	}
}
